import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建Axios实例
const api = axios.create({
  baseURL: 'http://localhost:8081/api',
  timeout: 60000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    ElMessage.error('请求发生错误，请稍后重试')
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 处理成功响应
    if (response.data && response.data.code !== 200) {
      ElMessage.warning(response.data.msg || '操作失败')
      return Promise.reject(response.data)
    }
    return response.data
  },
  error => {
    // 处理错误响应
    const status = error.response?.status
    switch (status) {
      case 401:
        ElMessage.error('身份验证失败，请重新登录')
        localStorage.removeItem('token')
        window.location.href = '/login'
        break
      case 403:
        ElMessage.error('没有权限执行此操作')
        break
      case 500:
        ElMessage.error('服务器内部错误，请稍后重试')
        break
      default:
        ElMessage.error(`请求错误: ${error.message}`)
    }
    return Promise.reject(error)
  }
)

// 聊天相关API
export const chatApi = {
  /**
   * 发送聊天消息
   * @param {Object} data - 聊天请求数据
   * @returns {Promise}
   */
  sendMessage: (data) => api.post('/chat/message', data),

  /**
   * 获取聊天历史
   * @param {string} sessionId - 会话ID
   * @returns {Promise}
   */
  getChatHistory: (sessionId) => api.get(`/chat/history/${sessionId}`),

  /**
   * 创建新会话
   * @returns {Promise}
   */
  createSession: () => api.post('/chat/session'),

  /**
   * 删除会话
   * @param {string} sessionId - 会话ID
   * @returns {Promise}
   */
  deleteSession: (sessionId) => api.delete(`/chat/session/${sessionId}`)
}

// 用户相关API
export const userApi = {
  /**
   * 获取用户信息
   * @returns {Promise}
   */
  getUserInfo: () => api.get('/user/info'),

  /**
   * 更新用户信息
   * @param {Object} data - 用户信息
   * @returns {Promise}
   */
  updateUserInfo: (data) => api.put('/user/info', data),

  /**
   * 登录
   * @param {Object} data - 登录信息
   * @returns {Promise}
   */
  login: (data) => api.post('/auth/login', data),

  /**
   * 登出
   * @returns {Promise}
   */
  logout: () => api.post('/auth/logout')
}

export default api